package com.ruoyi.web.controller.story;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Message;
import com.ruoyi.system.domain.Story;
import com.ruoyi.system.service.IMessageService;
import com.ruoyi.system.service.IStoryService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;

import com.ruoyi.system.service.impl.TaskServiceImpl;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 小事说
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/story")
public class StoryController  extends BaseController
{
    @Autowired
    private IStoryService storyService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private IMessageService messageService;

    @Autowired
    private QueClassificationService queClassificationService;

    @Autowired
    private DepartmentInfoService departmentInfoService;

    @Autowired
    private SysEmployeeService sysEmployeeService;

    @Autowired
    private StorySysEmployeeService storySysEmployeeService;

    @Autowired
    private TaskService taskService;

    private String prefix = "story/story";
    private String prefix2 = "story/admin";
    private String prefix3 = "story/progress";

    /**
     * 移动端小事发布页面跳转
     * @return
     */
    @RequiresPermissions("story:story:view")
    @GetMapping("/story")
    public String story()
    {
        return prefix + "/story";
    }

    /**
     * pc 移动端小事发布页面跳转
     * @return
     */
    @RequiresPermissions("story:chatsearch:view")
    @GetMapping("/chatsearch/{id}")
    public String chatsearch(@PathVariable("id") int id,ModelMap mmap)
    {
        mmap.put("id",id);
        //根据storyId去查询studentId
        int studentId = storyService.getStudentIdById(id);
        String IM_ACCOUNT = "";
//        studentId
        System.out.println("IM_ACCOUNT = " + studentId);
        if (String.valueOf(studentId).length() == 10){
            //根据KEY_ID查询IM_ACCOUNT
            IM_ACCOUNT = storyService.getStuImByKeyId(String.valueOf(studentId));
        }else {
            IM_ACCOUNT = storyService.getEmpImByKeyId(String.valueOf(studentId));
        }

        System.out.println("IM_ACCOUNT = " + IM_ACCOUNT);

        mmap.put("imAccount",IM_ACCOUNT);

        storyService.updateMychatcountZero(id);
        return prefix + "/message2";
    }




    /**
     * 移动端小事发布页面跳转
     * @return
     */
    @RequiresPermissions("story:webchat:view")
    @GetMapping("/webchat")
    public String webchat()
    {
        return prefix + "/webchat";
    }

    /**
     * pc端小事进度条信息展示页面跳转
     * @return
     */
    @RequiresPermissions("story:progress:view")
    @GetMapping("/progress")
    public String progress(@RequestParam("id") int id, ModelMap mmap)
    {
        Story story = storyService.selectStateById(id);
        mmap.put("id", story.getId());
        mmap.put("handleState", story.getHandleState());
        mmap.put("problem", story.getProblem());
        return prefix3 + "/progress";
    }

    /**
     * 根据学生Id展示移动端小事
     * @return
     */
    @RequiresPermissions("story:storylist:view")
    @GetMapping("/storylist")
    public String stroyList()
    {
        return prefix + "/storylist";
    }


    /**
     * 根据学生Id展示移动端小事
     * @return
     */
    @RequiresPermissions("story:selectStoryList:view")
    @PostMapping("/selectStoryList/{studentId}")
    @ResponseBody
    public List<Story> selectStroyListByStudentId(@PathVariable("studentId") int studentId)
    {
        //查询登陆的学生信息的id，传到下面去
        return storyService.selectStroyListByStudentId(studentId);
    }
    /**
     * pc端小事信息展示页面跳转
     * @return
     */
    @RequiresPermissions("story:admin:view")
    @GetMapping("/admin")
    public String admin(ModelMap mmap)
    {
        mmap.put("sumCount",  storyService.selectSumChatCount());
        return prefix2 + "/admin";
    }

    /**
     * 移动端对话框页面跳转
     * @return
     */
    @RequiresPermissions("chat:chatAndroid:view")
    @GetMapping("/chatAndroid")
    public String chat()
    {
        return prefix + "/message";
    }

    /**
     * 全部的小事信息
     *
     * @return
     */
    @RequiresPermissions("story:admin:list")
    @PostMapping("/admin/list")
    @ResponseBody
    public TableDataInfo list(String studentId, String classID, String departmentID, String beginTime, String endTime) throws Exception {
        System.out.println("studentId = " + studentId);
        System.out.println("classID = " + classID);
        System.out.println("departmentID = " + departmentID);
        System.out.println("beginTime = " + beginTime);
        System.out.println("endTime = " + endTime);

        startPage();
        List<Story> list = storyService.selectStoryList(studentId, classID, departmentID, beginTime, endTime);

//        String flag = studentId + classID + departmentID;
//        if (StringUtils.isNotEmpty(beginTime) && StringUtils.isEmpty(flag)){  //当开始时间不为空时，才需要用时间去过滤
//            List<Story> lists = new ArrayList<>();
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
//            Date start = format.parse(beginTime);
//            Date end = null;
//            if (StringUtils.isEmpty(endTime)) //如果没有传入结束时间就默认是今天
//                end = new Date();
//            else
//                end = format.parse(endTime);
//
//
//            long startTimes = start.getTime();
//            long endTimes = end.getTime();
//
//            System.out.println("startTimes = " + startTimes);
//
//            System.out.println("endTimes   = " + endTimes);
//
//            for (Story story : list) {
//                Date storyTime = story.getDate();
//                String format1 = format.format(storyTime);
//                Date parse = format.parse(format1);
//                long nowTimes = parse.getTime();
//
//                if (nowTimes >= startTimes && nowTimes <= endTimes){
//                    System.out.println("nowTimes   = " + nowTimes);
//                    lists.add(story);
//                }
//
//            }
//                list = lists;
//        }



//        List<Story> list = new ArrayList<>();
        return getDataTable(list);
    }

    @RequiresPermissions("story:admin:list")
    @PostMapping("/progress/storyInfo/{id}")
    @ResponseBody
    public Story StoryById(@PathVariable("id") Long id)
    {
        return storyService.selectStoryById(id);
    }

//    @RequiresPermissions("story:admin:list")
//    @PostMapping("/admin/list2")
//    @ResponseBody
//    public TableDataInfo list2(Story story)
//    {
//        startPage();
//        //查找message里面所有的id并且排序
//
////        List<Story> list = storyService.selectStoryList(story);
//        for (Story story1 : list) {  //遍历所有的story取出其中的id
//            story1.setStatusCount(messageService.selectStoryStatusCount(story1.getId())); // 根据id查询message中对应的status总数
//        }
////        Collections.sort(list, new Comparator<Story>(){
////            public int compare(Story s1, Story s2) {
////                return s2.getStatusCount()-s1.getStatusCount();
////            }});
//        return getDataTable(list);
//    }
    @RequiresPermissions("story:story:insert")
    @PostMapping("/story/insert")
    @ResponseBody
    public int insert(
            @RequestParam("problem") String problem,
            @RequestParam("programme") String programme,
            @RequestParam("pic") String pic,
            @RequestParam("remarks") String remarks,
            @RequestParam("referState") int referState,
            @RequestParam("studentId") String studentId)
    {
        Story story = new Story();
        story.setProblem(problem);
        story.setProgramme(programme);
        story.setPic(pic);
        story.setStudentId(studentId);
        story.setRemarks(remarks);
        story.setReferState(referState);
        story.setDate(new Date());
        if(storyService.insertStory(story)){
            return story.getId();
        }else{
            return 0;
        }
    }
    /**
     * 修改小事
     */
    @GetMapping("/admin/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        mmap.put("story", storyService.selectStoryById(id));
        return prefix2 + "/edit";
    }

    @RequiresPermissions("story:admin:remove")
    @Log(title = "小事管理", businessType = BusinessType.DELETE)
    @PostMapping("/admin/remove")
    @ResponseBody
    @Transactional
    public AjaxResult remove(String ids)
    {
        try
        {
            System.out.println(ids);
            //根据删除story_sysemployee的数据
            toAjax(storyService. deleteStorySByIds(ids));
            //根据删除messages的数据
            toAjax(storyService.deleteMessageByIds(ids));
            //根据删除story的数据
            return toAjax(storyService.deleteStoryByIds(ids));
        }
        catch (Exception e)
        {
            return error(e.getMessage());
    }
    }


    @RequiresPermissions("story:message:insert")
    @PostMapping("/message/insert")
    @ResponseBody
    @Transactional
    public boolean insertMessage(
            @RequestParam("storyId") int storyId,
            @RequestParam("information") String information,
            @RequestParam("fromToState") int fromToState,
            @RequestParam("studentId") String studentId)
    {
        Message message = new Message();
        message.setTime(new Date());
        message.setStudentId(studentId);
        message.setTeacherId(1);
        message.setStoryId(storyId);
        message.setFromToState(fromToState);
        message.setInformation(information);
        boolean result = storyService.updateStatusCount(storyId);
        if(!result){
            return false;
        }
        return messageService.insertMessage(message);
    }


    @RequiresPermissions("story:message:list")
    @PostMapping("/message/list/{storyId}")
    @ResponseBody
    public List<Message> selectMessageList(@PathVariable("storyId")int storyId)
    {
        return  messageService.selectMessageList(storyId);
    }

    @RequiresPermissions("system:admin:manage")
    @Log(title = "管理进度", businessType = BusinessType.OTHER)
    @GetMapping("/admin/manage/{id}")
    public String manage(@PathVariable("id") int id, ModelMap mmap){
        System.out.println(id);
        Story story = storyService.selectStateById(id);
        mmap.put("id", story.getId());
        mmap.put("handleState", story.getHandleState());
        mmap.put("problem", story.getProblem());
        mmap.put("handleTime", story.getHandleTime());
        mmap.put("forcedSubmitOrder", story.getIsForcedSubmit());

//        int handleState = storyService.selectStateById(id);
        return prefix2 + "/manage";
    }


//    @RequiresPermissions("system:admin:manage")
    @Log(title = "修改进度处理的状态", businessType = BusinessType.UPDATE)
    @GetMapping("/admin/updateHandleState")
    @ResponseBody
    @Transactional
    public String updateHandleState(int handleState, int id){
        int result = storyService.updateHandleStateAndHandleTime(id, handleState, null);
        if (result == 1){
            return "success";
        }else{
            return "fail";
        }
    }

    @Log(title = "修改直接成功的进度处理的状态", businessType = BusinessType.UPDATE)
    @GetMapping("/admin/updateHandleStateByCompletion")
    @ResponseBody
    @Transactional
    public String updateHandleStateByCompletion(int handleState, int id){
        int result = storyService.updateHandleStateByCompletion(id, handleState);
        if (result == 1){
            return "success";
        }else{
            return "fail";
        }
    }



    @Log(title = "修改进度处理的状态和退回状态", businessType = BusinessType.UPDATE)
    @GetMapping("/admin/updateHandleStateAndBack")
    @ResponseBody
    @Transactional
    public String updateHandleStateAndBack(@RequestParam("handleState") int handleState, @RequestParam("storyId") int storyId, @RequestParam("transferNumber") int transferNumber){
        System.out.println("transferNumber = " + transferNumber);
        int result = storyService.updateHandleStateAndHandleTime(storyId, handleState, null);
        int i = storySysEmployeeService.updateBack(storyId, transferNumber);
        return null;
    }

    @Log(title = "设置为无效状态", businessType = BusinessType.UPDATE)
    @GetMapping("/admin/invalidHandleState")
    @ResponseBody
    @Transactional
    public int invalidHandleState(int id){
        return storyService.invalidHandleState(id);
    }



    @RequiresPermissions("story:admin:manageMobile")
    @Log(title = "管理进度", businessType = BusinessType.OTHER)
    @GetMapping("/admin/manageMobile/{id}")
    public String manageMobile(@PathVariable("id") int id, ModelMap mmap){
        System.out.println(id);
        Story story = storyService.selectStateById(id);
        mmap.put("id", story.getId());
        mmap.put("handleState", story.getHandleState());
        mmap.put("problem", story.getProblem());
//        int handleState = storyService.selectStateById(id);
        return prefix2 + "/manage";
    }


    @Log(title = "根据id查询小事分类", businessType = BusinessType.OTHER)
    @GetMapping("/admin/selectClassById")
    @ResponseBody
    public List<QueClassification> selectClassById(@RequestParam("storyId") int id){
        return storyService.selectClassById(id);
    }

    @Log(title = "查询小事分类", businessType = BusinessType.OTHER)
    @GetMapping("/admin/selectClassList")
    @ResponseBody
    public List<QueClassification> selectClassList(){
        return queClassificationService.selectClassList();
    }


    @Log(title = "查询部门", businessType = BusinessType.OTHER)
    @GetMapping("/admin/selectDepartmentInfoList")
    @ResponseBody
    public List<DepartmentInfo> selectDepartmentInfoList(){
        return departmentInfoService.selectDepartmentInfoList();
    }

    @Log(title = "根据部门查询人员", businessType = BusinessType.OTHER)
    @GetMapping("/admin/selectSysEmployeeByOrganizationCode/{ORGANIZATION_CODE}")
    @ResponseBody
    public List<SysEmployee> selectSysEmployeeByOrganizationCode(@PathVariable("ORGANIZATION_CODE") String ORGANIZATION_CODE){
        return sysEmployeeService.selectSysEmployeeByOrganizationCode(ORGANIZATION_CODE);
    }

    @Log(title = "新增小事和转交的部门人员", businessType = BusinessType.OTHER)
    @PostMapping("/admin/insertStoryAndSysEmployee")
    @ResponseBody
    public int insertStoryAndSysEmployee(@RequestParam("storyID")int storyId,
                                         @RequestParam("classID")int classId,
                                         @RequestParam("departmentID[]")List<Integer> departmentIds,
                                         @RequestParam("sysEmployeeID[]")List<String> sysEmployeeIds,
//                                         @RequestParam("values")List<String[]> values,
                                         @RequestParam("opinion")String opinion){

        Long userId = ShiroUtils.getUserId();
        //添加当前时间
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        //确定出这条小事说转交了几次
        int transferNumber = storySysEmployeeService.determineTransferNumber(storyId);
        for (int i = 0; i < departmentIds.size(); i++) {
            Integer departmentId = departmentIds.get(i);
            String sysEmployeeId = sysEmployeeIds.get(i);


            SysEmployee sysEmployee = sysEmployeeService.selectNameById(sysEmployeeId);
            StorySysEmployee storySysEmployee = new StorySysEmployee();
            storySysEmployee.setUserId(userId);
            storySysEmployee.setStoryId(storyId);
            storySysEmployee.setClassId(classId);
            storySysEmployee.setDepartmentId(departmentId);
            storySysEmployee.setDepartmentName(sysEmployee.getORGANIZATION_NAME());
            storySysEmployee.setSysEmployeeId(sysEmployeeId);
            storySysEmployee.setSysEmployeeName(sysEmployee.getSYS_NAME());
            storySysEmployee.setOpinion(opinion);
            storySysEmployee.setTransferNumber(transferNumber);

            storySysEmployee.setOpinionTime(dateFormat.format(now));

            int i1 = storySysEmployeeService.insertStoryAndSysEmployee(storySysEmployee);
            int i2 = storyService.updateClassId(storyId, classId);
        }


        return 0;
    }

    @Log(title = "查询部门名称和人员名称", businessType = BusinessType.OTHER)
    @GetMapping("/admin/selectSysEmployeeNameAndOrganizationNameAndOpinion")
    @ResponseBody
    public List<StorySysEmployee> selectSysEmployeeNameAndOrganizationNameAndOpinion(@RequestParam("storyId") String storyId, @RequestParam("transferNumber")int transferNumber){
        List<StorySysEmployee> storySysEmployee = storySysEmployeeService.selectNameAndOpinionById(storyId, transferNumber);
        return storySysEmployee;
    }

    @Log(title = "查询第一次回复的信息", businessType = BusinessType.OTHER)
    @GetMapping("/admin/selectReply")
    @ResponseBody
    public List<StorySysEmployee> selectReply(@RequestParam("storyId")int storyId, @RequestParam("transferNumber")int transferNumber){
        return storySysEmployeeService.selectReply(storyId, transferNumber);
    }

    @Log(title = "查询审核意见，数据回显", businessType = BusinessType.OTHER)
    @GetMapping("/admin/selectOpinion")
    @ResponseBody
    public String selectOpinion(@RequestParam("storyId")int storyId){
        return storySysEmployeeService.selectOpinion(storyId);

    }

    @Log(title = "测试", businessType = BusinessType.OTHER)
    @GetMapping("/admin/selectMap")
    @ResponseBody
    public Map<Integer, String> selectMap(){
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "www");
        return map;

    }

    @Log(title = "更新回复消息的状态", businessType = BusinessType.UPDATE)
    @GetMapping("/admin/updateReplyStateByCompletion")
    @ResponseBody
    public int updateReplyStateByCompletion(
            @RequestParam("handleState")int handleState,
            @RequestParam("storyId")int storyId,
            @RequestParam("replyId")int replyId,
            @RequestParam("isBack")int isBack,
            @RequestParam("transferNumber")int transferNumber
    ){
        int count = storySysEmployeeService.updateHandleState(storyId, replyId, handleState, isBack, transferNumber);
        if (count == 0){
            return -1;
        }else{
            //需要返回出该移交信息的状态，用来页面的渲染
            return 2;
        }
    }


    @Log(title = "更新已完成的答复结果", businessType = BusinessType.UPDATE)
    @GetMapping("/admin/updateOpinion")
    @ResponseBody
    @Transactional
    public String updateOpinion(int handleState, int id, String opinion){
//        int result = storyService.updateOpinion(id, opinion);
        int result = storyService.updateHandleStateAndHandleTime(id, handleState, opinion);
        if (result == 1){
            return "success";
        }else{
            return "fail";
        }
    }

//    selectStoryOpinion
    @Log(title = "查询小事结果的答复", businessType = BusinessType.OTHER)
    @GetMapping("/admin/selectStoryOpinion")
    @ResponseBody
    public Story selectStoryOpinion(@RequestParam("storyId") String storyId){
        return storyService.selectStoryOpinion(Integer.parseInt(storyId));
    }


    @Log(title = "催办", businessType = BusinessType.OTHER)
    @GetMapping("/admin/cuiBan")
    @ResponseBody
    public String cuiBan(String storyId, int transferNumber){
        storySysEmployeeService.cuiBan(storyId, transferNumber);
        return "";
    }

    @Log(title = "forcedSubmit", businessType = BusinessType.UPDATE)
    @GetMapping("/admin/forcedSubmit")
    @ResponseBody
    public String forcedSubmit(String storyId, int forcedSubmitOrder){
        System.out.println("storyId = " + storyId);
        System.out.println("forcedSubmitOrder = " + forcedSubmitOrder);
        storyService.updateIsForcedSubmitByIdAndHandleState(Integer.parseInt(storyId), forcedSubmitOrder);
        return "";
    }

    @Log(title = "selectForcedSubmitTime", businessType = BusinessType.OTHER)
    @GetMapping("/admin/selectForcedSubmitTime")
    @ResponseBody
    public String selectForcedSubmitTime(String storyId){


        return storyService.selectForcedSubmitTime(Integer.parseInt(storyId));
    }




    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
//    @RequiresPermissions("system:story:export")
    @PostMapping("/admin/export")
    @ResponseBody
    public AjaxResult export(String ids)
    {
        System.out.println("ids ============================================== " + ids);
        List<ExportStory> list = storyService.exportStory(ids);
        ExcelUtil<ExportStory> util = new ExcelUtil<ExportStory>(ExportStory.class);
        return util.exportExcel(list, "角色数据");
    }
}
